﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BL;
using OrderDesk.Controllers;
using DA;
using BL.Membership;
using BaseLib.Localiztion;

namespace OrderDesk.Areas.OrdersStation.Controllers
{
    [AuthorizePage(UserPermission.OrdersStation)]
    public class OrdersController : BaseController
    {
        protected override void Execute(System.Web.Routing.RequestContext requestContext)
        {
            if (requestContext.HttpContext.Request.QueryString.AllKeys.Contains("deptId"))
            {
                ViewBag.DeptId = requestContext.HttpContext.Request.QueryString["deptId"].ToString();
            }
            else if (requestContext.HttpContext.Request.QueryString.AllKeys.Contains("catId"))
            {
                int catId = int.Parse(requestContext.HttpContext.Request.QueryString["catId"].ToString());
                ViewBag.DeptId = new CategoriesRepository().GetEntity(catId).DeptId;
            }
            ViewBag.OrderId = (requestContext.HttpContext.Request.QueryString["orderId"] ?? "").ToString();
            base.Execute(requestContext);
        }

        public ActionResult Index()
        {
            return RedirectToAction("departments");
        }

        public ActionResult CreateOrder(int? buyerId, int deptId)
        {
            if (!buyerId.HasValue)
            {/*
                BuyersRepository buyersRepository = new BuyersRepository();
                Buyer buyer = buyersRepository.Create(new Buyer() { ClientId = this.CurrentUser.ClientId });

                buyerId = buyer.BuyerId;*/
            }

            OrdersRepository ordersRep = new OrdersRepository();
            Order order = ordersRep.Create(new Order { BuyerId = buyerId, ClientId = CurrentUser.ClientId });

            return RedirectToAction("Categories", new { orderId = order.OrderId, deptId = deptId });
        }

        public ActionResult Departments(int? buyerId)
        {
            DepartmentsRepository depRep = new DepartmentsRepository();

            return View(depRep.GetEntitySet());
        }

        public ActionResult Categories(int orderId, int deptId)
        {
            CategoriesRepository catRep = new CategoriesRepository();
            return View(catRep.GetEntitySet().Where(x => x.DeptId == deptId));
        }

        public ActionResult Items(int orderId, int catId)
        {
            ItemsRepository itemRep = new ItemsRepository();

            return View(itemRep.GetEntitySet().Where(x => x.CategoryId == catId));
        }

        public ActionResult EditSingleOrderItem(int itemId)
        {
            var model = new ItemsInOrder();
            model.ItemId = itemId;

            ViewBag.Slices =
                new SlicesRepository()
                .GetEntitySet()
                .Where(x => x.ItemSlices.Any(s => s.ItemId == itemId))
                .Select(x => new { Name = x.Name, SliceId = x.SliceId })
                .ToList()
                .Select(x => new SelectListItem() { Text = x.Name, Value = x.SliceId.ToString() });

            ViewBag.ItemStatuses =
                new ItemInOrderStatusesRepository()
                .GetEntitySet()
                .ToList()
                .Select(x => new SelectListItem() { Text = x.Name, Value = x.StatusId.ToString() });

            return View("_OrderItem");
        }

        [HttpPost]
        public JsonResult CreateItemInOrder(ItemsInOrder itemInOrder)
        {
            var rep = new ItemsInOrdersRepository();

            itemInOrder = rep.Create(itemInOrder);

            return Json(GetItemsInOrder(itemInOrder.OrderId));
        }

        [HttpPost]
        public JsonResult GetItemsInOrder(int orderId)
        {
            var itemInOrders =
                new ItemsInOrdersRepository()
                .GetEntitySet()
                .Where(x => x.OrderId == orderId)
                .ToList()
                .Select(x => new
                {
                    name = x.Item.ItemName,
                    quantity = x.Quantity + " " + Translator.Translate(x.Item.MeasurementUnit.Name),
                    itemInOrderId = x.ItemInOrderId,
                    slice = x.Slice.Name
                });

            return Json(itemInOrders);
        }

        [HttpPost]
        public JsonResult DeleteItemsInOrder(int itemInOrderId)
        {
            return Json(new ItemsInOrdersRepository().Delete(itemInOrderId) > 0);
        }

        public ActionResult EndOrder(int orderId)
        {
            OrdersRepository rep = new OrdersRepository();
            Order order = rep.GetEntity(orderId, "ItemsInOrders");

            if (order == null)
                return RedirectToAction("Index");

            if (!order.ItemsInOrders.Any())
                rep.Delete(orderId);
            else
            {
                order.OrderStatusNum = (int)OrderStatusEnum.Pending;
                rep.Save(order);
            }

            return RedirectToAction("Index");
        }

        public ActionResult CancelOrder(int orderId)
        {
            OrdersRepository ordersRep = new OrdersRepository();
            ItemsInOrdersRepository itemsInOrdersRep = new ItemsInOrdersRepository();

            var itemsInOrderIds =
                itemsInOrdersRep.GetEntitySet()
                    .Where(x => x.OrderId == orderId)
                    .Select(x => x.ItemInOrderId)
                    .ToList();

            itemsInOrdersRep.Delete(itemsInOrderIds);

            ordersRep.Delete(orderId);

            return RedirectToAction("Index");
        }
    }
}
